package net.csdn.business.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author likun
 * @date 2022/7/8 12:24
 */
@Slf4j
public class ThreadUtil {

    public static void shutdownAndAwaitTermination(ExecutorService pool) {
        shutdownAndAwaitTermination(pool, 30);
    }

    public static void shutdownAndAwaitTermination(ExecutorService pool, int timeout) {
        if (pool != null && !pool.isShutdown()) {
            pool.shutdown();
            try {
                if (!pool.awaitTermination(timeout, TimeUnit.SECONDS)) {
                    log.info("Pool await terminate");
                    pool.shutdownNow();
                    if (!pool.awaitTermination(timeout, TimeUnit.SECONDS)) {
                        log.info("Pool did not terminate");
                    }
                }
            } catch (InterruptedException ie) {
                log.error("shutdown InterruptedException...");
                pool.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }
}